package com.cltech.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;


public final class IPUtil {
    /**
     * REALIP.
     */
    private static final String REALIP = "X-Real-IP";
    /**
     * X-Forwarded-For.
     */
    private static final String FORWARD = "X-Forwarded-For";
    /**
     * Proxy-Client-IP.
     */
    private static final String PROXY_CLIENT_IP = "Proxy-Client-IP";
    /**
     * WL-Proxy-Client-IP.
     */
    private static final String WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";
    /**
     * unknown.
     */
    private static final String UNKNOWN = "unknown";
    /**
     * 本地ip4.
     */
    private static final String LOCAL_IPV4 = "127.0.0.1";
    /**
     * 本地ip6.
     */
    private static final String LOCAL_IPV6 = "0:0:0:0:0:0:0:1";

    /**
     * 日志服务.
     */
    private static Logger logger = LoggerFactory.getLogger(IPUtil.class);

    /**
     * 获取请求发起人ip地址.
     *
     * @param request 请求
     * @return 远征地址
     */
    public static String getRemoteAddress(final HttpServletRequest request) {
        String ipAddress = request.getHeader(REALIP);
        int type = 1;
        if (StringUtils.isEmpty(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(FORWARD);
            type = 2;
        }
        if (StringUtils.isEmpty(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(PROXY_CLIENT_IP);
            type = 3;
        }
        if (StringUtils.isEmpty(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(WL_PROXY_CLIENT_IP);
            type = 4;
        }
        if (StringUtils.isEmpty(ipAddress) || UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            type = 5;
            if (ipAddress.equals(LOCAL_IPV4) || ipAddress.equals(LOCAL_IPV6)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (final UnknownHostException e) {
                    logger.error("get local ip error " + e);
                }
                ipAddress = inet.getHostAddress();
                type = 6;
            }
        }
        logger.info("request ip:{} type:{}", ipAddress, type);
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (!StringUtils.isEmpty(ipAddress) && !UNKNOWN.equalsIgnoreCase(ipAddress)) {
            final int index = ipAddress.indexOf(',');
            if (index > -1) {
                ipAddress = ipAddress.substring(0, index);
            }
        }
        return ipAddress;
    }
}
